package com.blic.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.blic.entity.Constant;
import com.blic.entity.UserInfoEntity;
import com.blic.entity.UserInfoEntity.UserStatus;
import com.blic.interceptor.Token;
import com.blic.service.api.IUserInfoService;
import com.blic.utils.DesUtil;
import com.blic.utils.Status;

@Controller
@RequestMapping("/userInfo")
public class UserInfoController {
	private final Logger logger = LoggerFactory.getLogger(UserInfoController.class);
	
	private final String REGISTER_URL = "/userInfo/register.htm";
	//private final String USERINFO_URL = "/userInfo/user.htm";
	
	//激活
	
	private final String ACTIVE_URL = "/userInfo/active.htm?params=";
	
	private final static String  SPELIT = ",";

	@Autowired
	public IUserInfoService userInfoService;
	
	@Value("${baseDaominName}")
	private String baseDaominName;
	
	@Value("${rootPath}")
	private String rootPath;
	
	@Value("${logoImg:}")
	private String logoImg;

	/**
	 * 跳转到用户注册页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/register")
	@Token(save=true)
	public ModelAndView register(HttpServletRequest request, HttpServletResponse response, Model model)
			throws ServletException, IOException {
		String openId = (String) request.getSession().getAttribute(Constant.SESSION_OPENID_KEY);
		UserInfoEntity userInfo = userInfoService.queryByOpenId(openId);

		
		if(userInfo == null) {
			logger.info("用户未注册过：{}",openId);
			return new ModelAndView("/userinfo/register");
		}else {
			if(userInfo != null){
				//已注册用户
				model.addAttribute("result", "不要重复注册哦~");
			}
		}
		
		return new ModelAndView("/result");
	}

	
	/**
	 * 绑定用户
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws ServletException
	 */
	@RequestMapping("/bind")
	@Token(remove=true)
	public ModelAndView bind(HttpServletRequest request, HttpServletResponse response, 
			UserInfoEntity userInfo,
			String operate,
			Model model)
			throws ServletException {
		
		String openId = (String) request.getSession().getAttribute(Constant.SESSION_OPENID_KEY);
		if(openId == null){
			return new ModelAndView("forward:"+REGISTER_URL);
			
		}
		
		UserInfoEntity userInfo1 = userInfoService.queryByOpenId(openId);
		
		if("update".equals(operate)){
			userInfo1.setUserFirstName(userInfo.getUserFirstName());
			userInfo1.setUserLastName(userInfo.getUserLastName());
			
			userInfo1.setUserEmployer(userInfo.getUserEmployer());
			userInfo1.setUserSex(userInfo.getUserSex());
			
			// 邮箱变更后，重发激活邮件
	 		if(userInfo.getUserEmail() != null && !userInfo1.getUserEmail().equals(userInfo.getUserEmail()) ){
				userInfo1.setUserEmail(userInfo.getUserEmail());
				userInfo1.setUserStatus(UserStatus.UNACTIVE.getKey());
			} 
		 
			userInfo1.setUserLocation(userInfo.getUserLocation());
			
		
			userInfo1.setUpdateTime(new Date());
			userInfo1.setIsNotify(Status.NotifyStatus.no.getKey());
			
			userInfoService.update(userInfo1);
			
			request.getSession().setAttribute(Constant.SESSION_USERINFO_KEY, userInfo1);
			model.addAttribute("result", "更新成功");
			
			
			
		}else{
			//绑定
			if(userInfo1 != null){
				//已注册用户
				//return new ModelAndView("forward:"+USERINFO_URL);
				if(UserStatus.ACTIVE.getKey().equals(userInfo1.getUserStatus())){
					model.addAttribute("result", "不要重复注册哦~");
				}else{
					model.addAttribute("result", "快到"+userInfo1.getUserEmail()+"邮箱激活账户吧!");
				}
				return new ModelAndView("/userinfo/bindResult.ftl");
			}
			if(userInfo != null) {
				userInfo.setOpenId(openId);
				userInfo.setCreateTime(new Date());
				userInfo.setUserStatus(UserStatus.UNACTIVE.getKey());
				
				userInfo.setUserPassWord(DesUtil.encode(userInfo.getUserPassWord(),DesUtil.DESUTIL_KEY ));
				userInfoService.insert(userInfo);
				
				model.addAttribute("result", "注册成功");
			}else {
				logger.info("未采集到用户信息** openId：{}",openId);
				model.addAttribute("result", "failure(注册未成功)");
			}
		}
		
		
		
		return new ModelAndView("result.ftl");
	}
	
	
	/**
	 * 查询用户信息
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws ServletException
	 */
	@RequestMapping("/user")
	public ModelAndView getUserInfo(HttpServletRequest request, HttpServletResponse response, 
			Model model)
			throws ServletException {
		String openId = (String) request.getSession().getAttribute(Constant.SESSION_OPENID_KEY);
		if(openId == null){
			return new ModelAndView("/userinfo/user.ftl");
		}
		UserInfoEntity userInfo = userInfoService.queryByOpenId(openId);
		
		if(userInfo != null && userInfo.getUserStatus().equals(UserStatus.ACTIVE.getKey()) ){
			model.addAttribute("user", userInfo);
		}else{
			return new ModelAndView("forward:"+REGISTER_URL);
		}
		
		return new ModelAndView("/userinfo/user.ftl");
	}
	
	
	/**
	 * 激活用户
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws ServletException
	 */
	@RequestMapping("/active")
	public ModelAndView active(HttpServletRequest request, HttpServletResponse response, Model model,String params)
			throws ServletException {
		 if(params != null){
			
			 //1 解密
			 //2 获取openid 和操作时间
			 //3判定时间，更新用户。
			 
			 params = DesUtil.decode(params, DesUtil.DESUTIL_KEY);
			 String arry[] = params.split(SPELIT);
			 
			 if(arry != null && arry.length == 2){
				 long reqTime = Long.valueOf(arry[0]);
				 String openId = arry[1];
				 
				 if(System.currentTimeMillis() - reqTime  < 3*60*60*1000){
					 //特定时间内有效
						UserInfoEntity userInfo = userInfoService.queryByOpenId(openId);
						if(userInfo != null  ){
							//有用户
							if(UserStatus.ACTIVE.getKey().equals(userInfo.getUserStatus())){
								model.addAttribute("result", "激活成功");
								model.addAttribute("succ", "1");
							}else{
								
								userInfo.setUserStatus(UserStatus.ACTIVE.getKey());
								userInfo.setUpdateTime(new Date());
								userInfo.setIsNotify(Status.NotifyStatus.no.getKey());
								this.userInfoService.update(userInfo);
								model.addAttribute("result", "激活成功");
								model.addAttribute("succ", "1");
							}
						}else{
							//无此用户
							 model.addAttribute("result", "激活失败，请重新注册");
						}
						
				 }else{
					 model.addAttribute("result", "请求已超时,请重新激活");
					 model.addAttribute("timeOutFlag","1");
					 model.addAttribute("params",DesUtil.encode(params, DesUtil.DESUTIL_KEY));
				 }
			 }else{
				 //激活失败
				 model.addAttribute("result", "激活失败，请重新注册");
			 }
		 }
		
		return new ModelAndView("/userinfo/bindResult.ftl");
	}
	
	
	/**
	 * 跳转到用户修改页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/update_index")
	@Token(save=true)
	public ModelAndView updateIndex(HttpServletRequest request, HttpServletResponse response, Model model)
			throws ServletException, IOException {
		String openId = (String) request.getSession().getAttribute(Constant.SESSION_OPENID_KEY);
		UserInfoEntity userInfo = userInfoService.queryByOpenId(openId);

		
		if(userInfo == null) {
			logger.info("用户未注册过：{}",openId);
			return new ModelAndView("/userinfo/register.ftl");
		}else {
			model.addAttribute("user", userInfo);
			return new ModelAndView("/userinfo/update.ftl");
		}
		
	}
	/**
	 * 跳转到用户修改页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/validateInfo")
	@ResponseBody
	public Object validateInfo(HttpServletRequest request, HttpServletResponse response,UserInfoEntity userInfo, Model model)
			throws ServletException, IOException {
		
		
		Map<String,String> map = new HashMap<String,String>();
		List<UserInfoEntity> userInfos = userInfoService.queryList(userInfo);
		
		if(userInfos.size() > 0){
			map.put("result", "no");
		}else{
			map.put("result", "ok");
		}
		return map;
	}
	
	
}
